package basicelement;


import istar.IElement;
import istar.agent.IstarJadeAgent;
import istar.behaviour.AbstractIstarBehaviour;
import istar.impl.AbstractBasicTask;
import istar.onto.IstarOntology;
import jade.content.lang.Codec;
import jade.content.lang.sl.SLCodec;
import jade.content.onto.Ontology;
import jade.core.AID;
import jade.core.Agent;
import jade.core.behaviours.Behaviour;
import jade.core.behaviours.OneShotBehaviour;
import jade.lang.acl.ACLMessage;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;

import log.Log;

import com.rapidminer.RapidMiner;
import com.rapidminer.example.Attribute;
import com.rapidminer.example.Example;
import com.rapidminer.example.ExampleSet;
import com.rapidminer.operator.IOContainer;
import com.rapidminer.operator.Operator;
import com.rapidminer.operator.io.ExampleSource;
import com.rapidminer.tools.OperatorService;

public class SeekStockQuotation extends AbstractBasicTask{

	private boolean log = true;
	private HashMap<String, String> quotations = null;
	private boolean done = false;
	
	public SeekStockQuotation() {
		super("SeekStockQuotation");
	}
	

	@Override
	public Behaviour getBehaviour() {
		//return new myBehaviour((IstarJadeAgent)this.getOwner(), this);
		return new myBehaviour(this);
	}
	
	private class myBehaviour extends AbstractIstarBehaviour{

		private int estimatedTime = 5000;
		boolean isFile = false;
		String testModel = "";
		
		
		
		
		public myBehaviour(AbstractBasicTask _task){
			super(_task);
			//task = _task;
			//this.setElement(_task);
			this.setBehaviourName("SeekQuotation");

		}
		
		@Override
		public long getEstimatedWaitingTime() {
			return estimatedTime;
		}

		
		@Override
		public void myAction() throws Exception {
			
			BufferedReader in = new BufferedReader(new FileReader(((IstarJadeAgent)myAgent).configurationPath));
		    String str;
		    while ((str = in.readLine()) != null) {
		        if (str.startsWith("TestModelFile=")){
		        	testModel = str.substring(14);
		        }
		    }
		    in.close();

			
            //IElement main = (IElement)((IstarJadeAgent)myAgent).getKnowledgeElement(this.getElement().getExecutionNumber(), this.getElement().getMain().getId()) ;
            Integer simulationStep=-1;
            // getting quotation parameter
            
            ACLMessage msg = ((IstarJadeAgent)myAgent).getWorkingMessages().get(getElement().getExecutionNumber());
				
            
          //changed here
			//String contentElement = (String)main.getContent().get(0);
            ArrayList<String> contentElement = (ArrayList<String>)((IstarJadeAgent)myAgent).getParameter(getExecutionNumber(), getElement().getName());
            
			for (int i = 0; i < contentElement.size(); i++) {
				if (contentElement.get(i).contains("SimulationStep=")){
					String content = contentElement.get(i);
					simulationStep = new Integer(content.substring(content.indexOf("SimulationStep")+15));
					break;
				}
			}
			System.out.println(simulationStep);
			//}

			Example example = this.getLastQuotationFromFile(simulationStep, testModel);
			
			ArrayList<String> response = new ArrayList<String>();

			ACLMessage reply = msg.createReply();
			msg.setPerformative(ACLMessage.INFORM);
            reply.setContentObject(example);

			myAgent.send(reply);
            done = true;
				
		}
		
		
		private Example getLastQuotationFromFile(int step, String pathToFile){
			Operator testSourceMax = null;
			try {
				testSourceMax = OperatorService.createOperator(ExampleSource.class);
			} catch (Exception e) { 
					// invoke init before using the OperatorService
					//RapidMiner.init(true, false, false, false);
					RapidMiner.init();
					System.out.println(this.getBehaviourName()+ " rodou RapidMiner.init()");
					try {
						testSourceMax = OperatorService.createOperator(ExampleSource.class);
					} catch (Exception e2) {
						e.printStackTrace();
					}
			}

			try {
				testSourceMax.setParameter("attributes", pathToFile);
				IOContainer containerMax = testSourceMax.apply(new IOContainer());
				ExampleSet resultSet = containerMax.get(ExampleSet.class);
				Attribute quotationTime= resultSet.getAttributes().getId();
				//RapidMiner.quit(0);
				return resultSet.getExample(step);
				
				// add operator to process
				//process.getRootOperator().addOperator(testSourceMax);
			} catch (Exception e) { 
				e.printStackTrace ();
				return null;
			}	

		}
		

		public int myOnEnd() {
			if (done){
				log("Agent name="+ myAgent.getName() +" ending behaviour:"+ this.getBehaviourName());
				return 1;
			}
			else
				return 0;
		}
		

		@Override
		public boolean done() {
			return true;
		}
		
	}
	

}
